package com.sinosoft.weixin.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * Created by 胡正莹 on 2017/11/09.
 */
@Configuration
@ImportResource("classpath:spring-mybatis.xml")
public class DbConfig {
  @Bean(destroyMethod = "close")
  public DataSource dataSource(@Value("${mailsys.db.jdbc.driverClass}") String driverClass,
                               @Value("${mailsys.db.jdbc.jdbcUrl}") String jdbcUrl,
                               @Value("${mailsys.db.jdbc.user}") String user,
                               @Value("${mailsys.db.jdbc.password}") String password,
                               @Value("${mailsys.db.jdbc.idleConnectionTestPeriod}") Integer idleConnectionTestPeriod,
                               @Value("${mailsys.db.jdbc.preferredTestQuery}") String preferredTestQuery) throws Exception{

    ComboPooledDataSource dataSource = new ComboPooledDataSource();
    dataSource.setDriverClass(driverClass);
    dataSource.setJdbcUrl(jdbcUrl);
    dataSource.setUser(user);
    dataSource.setPassword(password);
    dataSource.setIdleConnectionTestPeriod(idleConnectionTestPeriod);
    dataSource.setPreferredTestQuery(preferredTestQuery);
    return dataSource;
  }

  @Bean
  public DataSourceTransactionManager txManager(@Autowired DataSource ds){
    DataSourceTransactionManager manager = new DataSourceTransactionManager();
    manager.setDataSource(ds);
    return manager;
  }
}
